package cn.base.Impl;

import cn.base.IBaseDao;
import cn.domain.PageBean;
import cn.utils.HQLHelper;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Properties;

/**
 * Created by HuangJX on 2017/3/1.
 */
//忽略unchecked警告信息，如List，ArrayList等会惊醒参数化产生的警告信息
@SuppressWarnings("unchecked")
public class IBaseDaoImpl<T> implements IBaseDao<T> {

    @Resource
    private SessionFactory sessionFactory;

    private Class<T> classz;

    public IBaseDaoImpl() {
        //获得实体类型
        ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
        Type[] type=genericSuperclass.getActualTypeArguments();
        classz= (Class<T>) type[0];
    }

    @Override
    public void save(T entity) {
        session().save(entity);
    }

    @Override
    public void delete(Long id){
        session().delete(session().get(classz, id));
    }

    @Override
    public void update(Object entity) {
        session().update(entity);
    }

    @Override
    public T getById(Long id) {
        return (T) session().get(classz, id);
    }

    @Override
    public List getByIds(Long[] ids) {
        String hql = "from " + classz.getSimpleName() + " where id in (:ids)";
        Query query = session().createQuery(hql);
        query.setParameterList("ids",ids);//一次复制多个
        return query.list();
    }

    @Override
    public List findAll() {
        String hql = "from " + classz.getSimpleName();
        return session().createQuery(hql).list();
    }

    /**
     * 创建公共分页方法
     * @param hqlHelper
     * @param currentPage
     * @return
     */
    @Override
    public PageBean getPageBean(HQLHelper hqlHelper, int currentPage) {
        int pageSize=getPageSize();
        int firstResult=(currentPage-1)*pageSize;
        String listHql=hqlHelper.getHqlList();
        String count=hqlHelper.getCountHql();
        List<Object> args=hqlHelper.getArgs();

       Query query= session().createQuery(listHql);
       if(args!=null&&args.size()>0){
           int index=0;
           for(Object o:args){
                query.setParameter(index++,o);
           }
       }
        query.setFirstResult(firstResult);
       query.setMaxResults(pageSize);
       List recordList=query.list();
       query=session().createQuery(count);
       if(args!=null&&args.size()>0){
            int index=0;
            for(Object o:args){
                query.setParameter(index++,o);
            }
        }
        Long recordCOunt= (Long) query.uniqueResult();
        return new PageBean(currentPage,pageSize,recordCOunt.intValue(),recordList);
    }

    public Session session() {
        return sessionFactory.getCurrentSession();
    }

    public int getPageSize() {
        int pageSize=10;
        Properties properties=new Properties();
        InputStream in=this.getClass().getClassLoader().getResourceAsStream("page.properties");
        try {
            properties.load(in);
            String str= (String) properties.get("pageSize");
            pageSize=Integer.parseInt(str);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

            try {
                if(in!=null){

                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return pageSize;
    }
}
